package com.pesking.core.sqlparser.processor;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.util.DateUtils;
import com.pesking.core.util.StringUtils;

public class DateSqlParameterHandler extends SqlParameterProcessor {
	@Override
	public String getTitle() {
		return "日期参数";
	}

	@Override
	public String getDescription() {
		return null;
	}

	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		sbSQL.append("?");
		processors.add(sqlParameter);
	}

	@Override
	public void setParameter(PreparedStatement ps, Parameter parameter, int index,SqlParameter sqlParameter) throws SQLException {
		String value = parameter.getParameter(sqlParameter.getName());
		if (StringUtils.isBlank(value) || "null".equals(value)) {
			ps.setNull(index, java.sql.Types.DATE);
		}
		else {
			java.sql.Date date = new Date(DateUtils.getDateFromString(value, DateUtils.CHINA_DATE_FORMAT).getTime());
			ps.setDate(index, date);
		}
	}

	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"D","DATE"});
	}

}
